package inits

import (
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"ser-server/basic/config"
)

func init() {
	InitConfig()
	InitMysql()
	InitRedis()
}

func InitConfig() {
	viper.SetConfigFile("config.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		log.Println("配置文件读取失败")
		return
	}
	err = viper.Unmarshal(&config.SerConfig)
	if err != nil {
		log.Println("配置文件解析失败")
		return
	}
	log.Println("viper is success")
}

func InitMysql() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:mysql_ymQNhr@tcp(14.103.235.213:3306)/day?charset=utf8mb4&parseTime=True&loc=Local"
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println(err)
		return
	}
	log.Println("mysql is success")
}

func InitRedis() {
	config.RDB = redis.NewClient(&redis.Options{
		Addr:     config.SerConfig.Redis.Addr,
		Password: config.SerConfig.Redis.Password, // no password set
		DB:       config.SerConfig.Redis.DB,       // use default DB
	})
	log.Println("redis is success")
}
